<template>
	<view class="sort-Header sort-position" v-show="seckill_goods.length>0">
		<text>封面图</text>
		<text>标题</text>
		<text>操作</text>
	</view>
	<view style="height: 90rpx;"></view>
	<view class="sort-Header sort-table" v-for="(item,index) in seckill_goods" :key="item._id">
		<image :src="item.cover" mode="aspectFill"></image>
		<text>{{item.title}}</text>
		<text class="sort-but" @click="Delete(item._id,index)">删除</text>
	</view>
	<!-- 没有数据的提示 -->
	<view class="Tips" v-if="seckill_goods.length==0">你还没有秒杀数据</view>
	<!-- 底部 -->
	<view style="300rpx"></view>
	<view class="newly-added-view">
		<view class="newly-added" @click="toggle('bottom')">创建秒杀</view>
	</view>
	<!-- 弹窗 -->
	<uni-popup ref="inputDialog" background-color="#fff">
		<view class="popup-content">
			<view class="space-view">
				<view class="modify-sub modify-padding">
					<image src="/static/detail/guanbi.svg" mode="widthFix" @click="gb"></image>
					<text>创建秒杀</text>
					<text class="sort-but" @click="subMit">提交</text>
				</view>
				<view class="upload-cover">
					<image src="/static/detail/miaosha-img.jpg" mode="aspectFill" @click="uploadImg" v-if="data.se_cover == ''"></image>
					<image :src="data.se_cover" mode="aspectFill" @click="previewImg"  v-show="data.se_cover!=''"></image>
					<image src="../../static/detail/shanchu-goods.svg" @click="data.se_cover=''" mode="widthFix" v-show="data.se_cover!=''"></image>
				</view>
				<view class="seckill-input">
					<input type="text" v-model="data.se_title" placeholder="请输入标题" placeholder-class="input-color" cursor-spacing="50">
					<input type="number" v-model="data.se_price" placeholder="请输入秒杀价" placeholder-class="input-color" cursor-spacing="50">
				</view>
				<!-- 设置时间 -->
				<view class="pick-Outer">
					<view class="pick-view Underline">
						<view>
							<text>设置开始时间</text>
							<!-- 滚动选择器 -->
							<picker class="flex-left" mode="multiSelector" :range="data.start_arr" :value="data.multiIndex_a"
								range-key="name" @columnchange="colStart" @change="changeStart">
								<view>
									<text class="pick-time">{{data.start}}</text>
									<image src="/static/detail/xiangyou-jiantou.svg" mode="widthFix"></image>
								</view>
							</picker>
						</view>
					</view>
					<!-- 结束时间 -->
					<view class="pick-view">
						<view>
							<text>设置结束时间</text>
							<!-- 滚动选择器 -->
							<picker class="flex-left" mode="multiSelector" :range="data.end_arr" :value="data.multiIndex_b"
								range-key="name" @columnchange="colEnd" @change="changeEnd">
								<view>
									<text class="pick-time">{{data.end}}</text>
									<image src="/static/detail/xiangyou-jiantou.svg" mode="widthFix"></image>
								</view>
							</picker>
						</view>
					</view>
				</view>
				<!-- 关联商品 -->
				<view class="relation relation-back" @click="addTo">
					<text>关联商品</text>
					<text class="over-text">{{data.re_goods.title=='' ? '添加' : data.re_goods.title}}</text>
				</view>
				<view style="height: 200rpx;"></view>
			</view>
		</view>
	</uni-popup>
</template>

<script setup>
	import {ref,reactive,onMounted,toRefs,watch} from 'vue'
	import {uploadImage,cloud,previewPicture} from '@/Acc-config/media.js'
	import {init} from '@/Acc-config/init.js'
	import {start_date,end_date} from '@/Acc-config/date.js'
	import {current,months,codays} from '@/Acc-config/ca-time.js'
	
	//滚动选择器-设置年份和月份
	current()
	
	let inputDialog= ref(null)
	// 打开弹窗的方法
	function toggle(type) {
		// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
		inputDialog.value.open(type)
	}
	// 关闭弹窗
	function gb(){
		inputDialog.value.close()
	}
	
	// 存储从数据库获取的数据
	const getDatabase=reactive({seckill_goods:[]})
	let {seckill_goods}=toRefs(getDatabase)
	
	
	onMounted(()=>{
		getData()
	})
	
	async function getData(){
		let db=await init()
		let result =await db.database().collection('seckill').get()
		getDatabase.seckill_goods=result.data
	}
	
	const data=reactive({
		start_arr:start_date,//秒杀开始时间
		end_arr:end_date,//秒杀结束时间
		multiIndex_a:[0,0,0,0,0],//多列选择器的每一项的值(下标) 分别对应年、月、日、时、分
		multiIndex_b:[0,0,0,0,0],
		se_cover:'',//封面图
		se_title:'',//标题
		se_price:'',//秒杀价格
		start:'',//确认秒杀时间
		end:'',//确认秒杀结束时间
		// 关联商品
		re_goods:{
			title:'',//关联的商品标题
			goods_id:'',//关联的商品id
			video_url:'',//关联的商品短视频
			ori_price:''//关联的商品原价
		},
		years:[{'year':start_date[0][0].time,'month':start_date[1][0].time}],
		ban:false//判断设置的秒杀时间是否正确
	})
	
	// 上传封面图
	async function uploadImg(){
		try{
			// 上传到本地-拿到返回的URL链接
			const upImg=await uploadImage()
			uni.showLoading({title:'正在上传',mask:true})
			// 将图片的URL链接上传到云存储
			const res=await cloud(upImg[0].tempFilePath)
			data.se_cover=res
			
			uni.hideLoading()
			uni.$showMsg('图片上传成功','succeed')
		}catch(e){
			//TODO handle the exception
			console.log(e)
			// uni.$showMsg('图片上传失败')
		}	
	}
	
	// 预览上传的封面图
	function previewImg(){
		previewPicture(data.se_cover,[data.se_cover])
	}
	
	// 秒杀开始时间：滚动选择器-滚动时触发
	function colStart(event){
		// console.log(event.detail)
		const RES=event.detail
		shAre(RES,data.start_arr,data.multiIndex_a,'start')
		
	}
	// 秒杀结束时间：滚动选择器-滚动时触发
	function colEnd(event){
		const RES = event.detail
		shAre(RES,data.end_arr,data.multiIndex_b,'end')
	}
	
	// 秒杀开始时间和结束时间滚动时触发公用方法：从新计算某年某月的天数
	function shAre(RES,to_date,mult,val){
		mult[RES.column] = RES.value
		switch(RES.column){
			case 0://滚动第一列:年
				switch(mult[0]){
					case 0://滚动第一列的第一个值：当前的年份
						to_date[1] = months(to_date[0][0].time)
						to_date[2] = codays({year:to_date[0][0].time,month:to_date[1][0].time})
						break;
					case 1://滚动第一列的第二个值：明年的年份
						to_date[1] = months(to_date[0][1].time)
						to_date[2] = codays({year:to_date[0][1].time,month:-1})
						break;
				}
				mult.splice(1,1,0)
				mult.splice(2,1,0)
				mult.splice(3,1,0)
				mult.splice(4,1,0)
			break;
			case 1://拖动第二列：月份
				let MO = mult
				to_date[2] = codays({year:to_date[0][MO[0]].time,month:to_date[1][MO[1]].time})
				mult.splice(2,1,0)
				mult.splice(3,1,0)
				mult.splice(4,1,0)
				break;
		}
	}
	
	// 开始时间：确定
	function changeStart(e){
		const RES = e.detail.value
		conFirm(RES,'start',data.start_arr)
	}
	// 结束时间：确定
	function changeEnd(e){
		const RES = e.detail.value
		conFirm(RES,'end',data.end_arr)
	}
	// 开始时间和结束时间：确定=》公用
	function conFirm(RES,val,date){
		const year = date[0][RES[0]].time
		const month = date[1][RES[1]].time
		const day = date[2][RES[2]].time
		const time = date[3][RES[3]].time
		const minute = date[4][RES[4]].time
		const sele_res = year + '/' + month + '/' + day + ' ' + time + ':' + minute + ':' + '00'
	
		if(val == 'start'){
			// 开始时间
			data.start = sele_res
			data.multiIndex_a = RES
		}else{
			// 结束时间
			data.end = sele_res
			data.multiIndex_b = RES
		}
		
	}	
	
	// 监听结束时间是否小于开始时间
	import moment from 'moment'
	moment.locale('zh-cn');
	watch([()=>data.start,()=>data.end],(newVal,oldVal)=>{
		if(newVal[0] != '' && newVal[1] != ''){
			const start = moment(newVal[0],'YYYY/MM/DD hh:mm:ss').unix()//开始时间
			const end = moment(newVal[1],'YYYY/MM/DD hh:mm:ss').unix()//结束时间
			if(start >= end){
				data.end = '结束时间早于开始时间'
				data.ban = false
			}else if(start < end){
				data.ban = true
			}
		}
	})
	
	
	// 关联商品
	function addTo(){
		let goods_id=getDatabase.seckill_goods.map(item=>item.goods_id)
		uni.navigateTo({
			url:`/pages/goods-list/goodsList?goods_id=${JSON.stringify(goods_id)}`
		})
	}
	// 监听关联的商品
	import {select_goods} from '@/Acc-config/answer.js'
	watch(select_goods,(newVal,oldVal)=>{
		data.re_goods.title = newVal.goods_title
		data.re_goods.goods_id = newVal.goods_id
		data.re_goods.video_url = newVal.video_url
		data.re_goods.ori_price = newVal.goods_price
	})
	
	// 提交
	function subMit(){
		switch(true){
			case data.se_cover=='' : uni.$showMsg('请上传封面图')
			break;
			case data.se_title=='' : uni.$showMsg('请输入标题')
			break;
			case data.se_price=='' : uni.$showMsg('请输入秒杀价')
			break;
			case data.start=='' || data.end=='' : uni.$showMsg('请设置秒杀时间')
			break;
			case data.ban==false : uni.$showMsg('结束时间早于开始时间')
			break;
			case data.re_goods.goods_id=='' : uni.$showMsg('请关联一个商品')
			break;
			default:database()
		}
	}
	// 将数据上传到数据库
	async function database(){
		// 将秒杀时间，转为时间戳
		const start_Time = moment(data.start,'YYYY/MM/DD hh:mm:ss').unix()
		const end_Time = moment(data.end,'YYYY/MM/DD hh:mm:ss').unix() 
		
		let obj = {
			cover:data.se_cover,
			title:data.se_title,
			ori_price:data.re_goods.ori_price,
			price_spike:Number(data.se_price),
			seckill_time:{start_Time,end_Time},
			goods_id:data.re_goods.goods_id,
			video_url:data.re_goods.video_url
		}
		
		try{
			uni.showLoading({
				title:'正在提交',
				mask:true
			})
			
			let db= await init()
			await db.database().collection('seckill').add({data:obj})
			// 查询该商品将秒杀字段改为return true
			await db.database().collection('goods').doc(data.re_goods.goods_id).update({data:{seckill:true}})
			gb()
			getData()
			
			uni.$showMsg('提交成功','success')
			
			uni.hideLoading()
			
			data.se_cover = '';data.se_title='';
			data.se_price = '';data.start = '';
			data.end = '';data.re_goods.title = ''
		}catch(e){
			//TODO handle the exception
			console.log(e)
			uni.$showMsg('提交失败')
		}
	}
	
	// 删除
	async function Delete(id,index){
		console.log(id)
		try{
			let db=await init();
			await db.database().collection('seckill').doc(id).remove()
			getDatabase.seckill_goods.splice(index,1)
			
			uni.$showMsg('删除成功','success')
		}catch(e){
			console.log(e)
			uni.$showMsg('删除失败')
		}	
	}

</script>

<style scoped>
	.space-view{
		height: 800rpx;
	}
	.sort-table text:nth-child(2) {
		color: #333333 !important;
		background-color: initial !important;
		border-radius: 0 !important;
		padding: 0 !important;
		font-size: 30rpx !important;
	}
	.modify-padding image{
		margin-right: 60rpx;
	}

	.modify-padding {
		padding-bottom: 60rpx !important;
	}

	.relation-back {
		background-color: #f7f7f7 !important;
		color: #000000 !important;
	}

	.over-text {
		color: #ed6b51 !important;
	}

	.upload-cover {
		position: relative;
	}

	.upload-cover image:nth-child(1) {
		width: 100%;
		height: 380rpx;
		display: block;
	}

	.upload-cover image:nth-child(2) {
		width: 40rpx;
		height: 40rpx;
		position: absolute;
		top: 6rpx;
		right: 6rpx;
	}

	.seckill-input input {
		padding: 20rpx;
		background-color: #f7f7f7;
		margin-top: 30rpx;
		border-radius: 7rpx;
	}

	/deep/ .input-color {
		color: #cccccc;
	}

	.pick-Outer {
		background-color: #f7f7f7;
		margin-top: 30rpx;
		padding: 0 20rpx;
		border-radius: 7rpx;
	}

	.pick-view {
		padding: 20rpx 0;
	}

	.pick-view image {
		display: block;
		width: 30rpx;
		height: 30rpx;
		margin-left: 20rpx;
	}

	.pick-view view:nth-child(1) {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.flex-left {
		flex: 1;
	}

	.flex-left view {
		justify-content: flex-end !important;
	}

	.Underline {
		border-bottom: 1rpx solid #ededed;
	}

	.pick-time {
		font-size: 27rpx;
	}
</style>